// user Controller
//数据模型
const Model = require("../DB/Model");
// 通过设置表名来调用查询方法
// const model = require("../DB/Model").setTable("zhipin.user"); // 引入模型

// 加密解密方法
const { encrypt, decrypt } = require("../utils/crypto");

// 登陆处理
async function loginController(req, res, next) {
  const { username, password } = req.body;
  try {
    var user = await Model.find("zhipin.user", { username });
    if (user.length === 0) {
      console.log("用户名不存在");
      res.send({ msg: "用户名不存在", code: 1 });
    } else {
      if (user[0].password !== encrypt(password)) {
        res.send({
          msg: "密码错误",
          code: 1
        });
      } else {
        const { zid } = user[0];
        res.cookie("zid", zid, { maxAge: 1000 * 60 * 60 * 24 });
        res.send({
          code: 0,
          data: user[0]
        });
      }
    }
  } catch (error) {
    res.send({
      msg: "登陆异常",
      code: 1
    });
  }
}
// 注册处理
async function registerController(req, res, next) {
  const { username, password, usertype } = req.body;
  try {
    const userModel = new Model("zhipin.user", {
      username,
      password: encrypt(password),
      usertype
    });
    const result = await userModel.save();
    const users = await Model.find("zhipin.user", { username });
    res.cookie("zid", users[0].zid, { maxAge: 1000 * 60 * 60 * 24 });
    res.send({ code: 0, data: users[0] });
  } catch (error) {
    const msg = error.sqlState === "23000" ? "用户已存在" : "注册出错";
    res.send({ msg, code: 1 });
  }
}
async function updateInfoController(req, res, next) {
  // 头像，求职/招聘职位，公司名称，薪水，个人介绍/职位描述
  const infos = req.body;
  const zid = req.cookies.zid;
  try {
    const users = await Model.find("zhipin.user", { zid });
    if (users.length === 0) {
      res.clearCookie("zid");
      return res.send({ code: 1, msg: "请登录" });
    }
    const result = await Model.update("zhipin.user", infos, { zid });
    res.send({ code: 0, data: Object.assign(users[0], infos) });
  } catch (error) {
    res.send({ code: 1, msg: "保存失败" });
  }
}
// 查询用户
async function getUserController(req, res, next) {
  const zid = req.cookies.zid;
  try {
    const users = await Model.find("zhipin.user", { zid });
    if (users.length === 0) {
      return res.send({ code: 1, msg: "登陆失败" });
    }
    res.send({ code: 0, data: users[0] });
  } catch (error) {
    return res.send({ code: 1, msg: "登陆错误" });
  }
}
// 查询返回用户对应用户类型的列表
async function getUserListController(req, res, next) {
  let { usertype } = req.query;
  if (usertype === "0") {
    usertype = "1";
  } else if (usertype === "1") {
    usertype = "0";
  }
  try {
    let users = await Model.find("zhipin.user", { usertype });
    users = users.filter(user => user.usertype === usertype);
    res.send({ code: 0, data: users });
  } catch (error) {
    res.send({ code: 1, msg: "获取用户列表失败", error });
  }
}

/** Message List Controller */
// 得到消息列表
async function getMessageListController(req, res, next) {
  const zid = req.cookies.zid;
  let userMap = {};
  try {
    let users = await Model.find("zhipin.user");
    users.forEach(user => {
      userMap[user.zid] = { username: user.username, avatar: user.avatar };
    });
    let chartList = await Model.find("zhipin.message", {
      or: { from_id: zid, to_id: zid }
    });
    res.send({ code: 0, data: { userMap, chartList } });
    // userMap = users.reduce((userMap, user) => {
    //   userMap[user.zid] = { username: user.username, avatar: user.avatar };
    //   return userMap;
    // }, {});
  } catch (error) {
    res.send({ code: 1, error });
  }
}
//读消息
async function readMessageController(req, res, next) {
  const from_id = req.body.from_id;
  const to_id = req.cookies.zid;
  console.log(from_id,to_id)
  try {
    let result = await Model.update(
      "zhipin.message",
      { isread: 1 },
      { from_id, to_id, isread: 0 }
    );
    res.send({ code: 0, data: result });
  } catch (error) {
    res.send({ code: 1, msg: "消息读取失败", error });
  }
}

module.exports = {
  loginController,
  registerController,
  updateInfoController,
  getUserController,
  getUserListController,
  getMessageListController,
  readMessageController
};
